package cn.le.service;

import cn.le.po.DeviceDataPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import static cn.le.util.Constant.PG_INSERT_SQL;

@Service
public class PgService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(rollbackFor = Exception.class)
    public void jdbcBachInsert(List<DeviceDataPO> list){
        jdbcTemplate.batchUpdate(PG_INSERT_SQL, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                DeviceDataPO po = list.get(i);
                ps.setLong(1,po.getDeviceId());
                ps.setLong(2,po.getPropertyId());
                ps.setString(3,po.getData());
                ps.setTimestamp(4,new Timestamp(po.getCollTime().getTime()));
                ps.setTimestamp(5,new Timestamp(po.getCreateAt().getTime()));
            }

            @Override
            public int getBatchSize() {
                return list.size();
            }
        });

    }
}
